package com.android.audyalarm;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.provider.AlarmClock;
import android.provider.MediaStore;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;

public class TestActivity extends Activity {

	final static String TAG = "ServiceTest3";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_test);

		Button scheduleButton = (Button)findViewById(R.id.scheduleButton);
		scheduleButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Log.d(TAG, "aaa");
				scheduleService();
			}
		});

		Button cancelButton = (Button)findViewById(R.id.cancelButton);
		cancelButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				cancelService();
			}
		});

		Button alarmButton = (Button)findViewById(R.id.alarmButton);
		alarmButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				setAndroidAlarm();


			}
		});

		playAudioButton = (Button)findViewById(R.id.playAudioButton);
		playAudioButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) { playAudio(); }
		});

			mp = new MediaPlayer();

		Button addAudioButton = (Button)findViewById(R.id.addAudioButton);
		addAudioButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) { addAlarmSound(); }
		});



		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item);

		//List<String> list = getAlarmSound();
		//for (int i = 0; i < list.size(); i++) {
		//	adapter.add(list.get(i));
		//}

		ContentResolver resolver = this.getContentResolver();
		Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Audio.Media.DATA}, null, null, null);
		cursor.moveToFirst();
		while(cursor.moveToNext()){
			adapter.add(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
		}

		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		Spinner spinner = (Spinner)findViewById(R.id.audioSpinner);
		spinner.setAdapter(adapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.test, menu);
		return true;
	}


	MediaPlayer mp = null;
	Button playAudioButton;

	private void playAudio() {
		if (!mp.isPlaying()) {
			Spinner spinner = (Spinner)findViewById(R.id.audioSpinner);

			try {
				String filePath = spinner.getSelectedItem().toString();


				MediaStore.Audio.Media.INTERNAL_CONTENT_URI.toString();
		        AlertDialog dialog = (new AlertDialog.Builder(this)).create();
		        dialog.setTitle("aaa");
		        dialog.setMessage(filePath);
		        dialog.show();

				mp.setDataSource(filePath);
				mp.prepare();
				mp.start();

				MediaMetadataRetriever mmr = new MediaMetadataRetriever();
				mmr.setDataSource(filePath);
				EditText t = (EditText)findViewById(R.id.alarmEditText);
				t.setText(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE));


				playAudioButton.setText("Stop Music");
			} catch (IllegalStateException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			} catch (IOException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			}
		} else {
			mp.stop();
			mp.reset();
			playAudioButton.setText("Start Music");
		}
	}

	private void addAlarmSound() {

		AudyAlarmDbOpenHelper helper = new AudyAlarmDbOpenHelper(getApplicationContext());
		SQLiteDatabase db = helper.getWritableDatabase();

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		ContentValues val;
		val = new ContentValues();
		val.put("alarm_id", 1);
		val.put("file_path", "/sdcard/anime/02.mp3");
		val.put("add_time", dateFormat.format(new Date()));
		db.insert("playlist", null, val);

		val = new ContentValues();
		val.put("alarm_id", 2);
		val.put("file_path", "/sdcard/anime/03.mp3");
		val.put("add_time", dateFormat.format(new Date()));
		db.insert("playlist", null, val);

		val = new ContentValues();
		val.put("alarm_id", 3);
		val.put("file_path", "/sdcard/anime/12.mp3");
		val.put("add_time", dateFormat.format(new Date()));
		db.insert("playlist", null, val);

		val = new ContentValues();
		val.put("alarm_id", 4);
		val.put("file_path", "/sdcard/anime/21.mp3");
		val.put("add_time", dateFormat.format(new Date()));
		db.insert("playlist", null, val);
	}

	private List<String> getAlarmSound() {
		List<String> list = new ArrayList<String>();

		AudyAlarmDbOpenHelper helper = new AudyAlarmDbOpenHelper(getApplicationContext());
		SQLiteDatabase db = helper.getReadableDatabase();


		Cursor c = db.query("playlist", new String[] { "file_path" }, null, null, null, null, null);
		boolean existsRow = c.moveToFirst();
		while (existsRow) {
			list.add(c.getString(0));
			existsRow = c.moveToNext();
		}

		c.close();
		db.close();

		return list;
	}


	protected void scheduleService() {
		Log.d(TAG, "scheduleService()");
		Context context = getBaseContext();
		Intent intent = new Intent(context, MyIntentService.class);

		PendingIntent pendingIntent = PendingIntent.getService(context, -1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
		alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), 5000, pendingIntent);
	}

	protected void cancelService() {
		Context context = getBaseContext();
		Intent intent = new Intent(context, MyIntentService.class);

		PendingIntent pendingIntent = PendingIntent.getService(context, -1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
		alarmManager.cancel(pendingIntent);
	}

	@SuppressLint("InlinedApi")
	private void setAndroidAlarm() {
		TimePicker timePicker = (TimePicker)findViewById(R.id.alarmTimePicker);
		int hour = timePicker.getCurrentHour();
		int min = timePicker.getCurrentMinute();
		Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM);
		intent.putExtra(AlarmClock.EXTRA_HOUR, hour);
		intent.putExtra(AlarmClock.EXTRA_MINUTES, min);

		EditText editText = (EditText)findViewById(R.id.alarmEditText);
		intent.putExtra(AlarmClock.EXTRA_MESSAGE, editText.getText().toString());

		startActivity(intent);
	}

}
